<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="video" content="width=device-width, initial-scale=1.8">
    <title>Document</title>
</head>
<body>
    <h1> 本地直播 </h1>
    <div id="local" style="width: 600px; height: 400px"></div>
    <h1> 远程直播 </h1>
    <div id="remote" style="width: 600px; height: 400px"></div>

    <script src="js/trtc.js"></script>
    <script src="js/lib-generate-test-usersig.min.js"></script>
    <script>
        // 使用腾讯云上注册的私钥进行服务认证
        const SDKAPPID = 1400515540;
        const SECRETKEY = '21bd87dcdc91066ecfe2f9ba305ca0a91fc980a92cd4ca35d59fafc2c56d18e9';
        const EXPIRETIME = 7*24*60*60
        const generator = new LibGenerateTestUserSig(SDKAPPID, SECRETKEY, EXPIRETIME)

        // TODO 从后台获取id
        const userId = parseInt(1000*Math.random()).toString()
        console.log("随机的用户ID：", userId)

        // 生成用户签名
        const userSig = generator.genTestUserSig(userId)

        // 建立客户端
        const client = TRTC.createClient({
            mode:'rtc',
            sdkAppId: SDKAPPID,
            userId,
            userSig,
        })

        client.useStringRoomId_=true
        let roomId = '000001'
        console.log(roomId)
        // 进入房间
        client.join({roomId}).catch((error)=>{
            console.log("进入房间失败：", error)
        }).then(()=>{
            console.log("创建房间成功")
            // 初始化本地流
            const localStream = TRTC.createStream({
                userId,
                audio:true,
                video:true
            })
            localStream.initialize().catch((error)=>{
                console.log("初始化本地流失败：", error)
            }).then(()=>{
                console.log("初始化本地流成功")
                localStream.play("local")

                // 发布本地视频流
                client.publish(localStream).catch((error)=>{
                    console.log("视频流发布失败",error)
                }).then(()=>{
                    console.log("视频流发布成功")
                })
            })

            // 订阅stream-added，监听远程流的增加事件
            client.on("stream-added", (event)=>{
                const remoteStream = event.stream
                console.log("远程视频流增加："+remoteStream.getId())
                client.subscribe(remoteStream)
            })

            // 订阅stream-subscribed，监听远程流的视频流发布事件
            client.on('stream-subscribed',(event)=>{
                const remoteStream = event.stream
                console.log("远程订阅成功："+remoteStream.getId())
                remoteStream.play("remote")
            })
        })

    </script>
</body>
</html>
